package snaptest.repo;

public class FilePath {

	private static final String SLASH = "/";
	private final String path;
	private final String[] pathSegments;

	public FilePath(String path) {
		this.path = path;
		this.pathSegments = path.split(SLASH);
	}

	public FilePath prependDirectory(String dir) {
		return new FilePath(dir + SLASH + path);
	}

	public String getPath() {
		return path;
	}

	public String getLastElement() {
		if (pathSegments.length == 0) {
			return "";
		} else {
			return pathSegments[pathSegments.length - 1];
		}
	}

	public FilePath removeFirstElement() {
		if (pathSegments.length <= 1) {
			return new FilePath("");
		} else {
			return new FilePath(joinSegments(1, pathSegments.length));
		}
	}

	public FilePath removeLastElement() {
		if (pathSegments.length <= 1) {
			return new FilePath("");
		} else {
			return new FilePath(joinSegments(0, pathSegments.length - 1));
		}
	}

	private String joinSegments(int startIndex, int endIndex) {
		StringBuilder sb = new StringBuilder();
		for (int i = startIndex; i < endIndex - 1; i++) {
			sb.append(pathSegments[i]).append(SLASH);
		}
		sb.append(pathSegments[endIndex - 1]);
		return sb.toString();
	}

	@Override
	public String toString() {
		return path;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((path == null) ? 0 : path.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		FilePath other = (FilePath) obj;
		if (path == null) {
			if (other.path != null)
				return false;
		} else if (!path.equals(other.path))
			return false;
		return true;
	}

}
